package com.jumi.microservice.rocketmq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.jumi.microservice.dto.userWallet.WalletInOrOutRequest;
import com.jumi.microservice.service.usercash.admin.AdminCpsWalletInOrOutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户结算队列监听
 * @author mazhao
 * @Date 2020-09-17 11:50
 */
@Component
public class CpsSettlementListener implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(CpsSettlementListener.class);

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    AdminCpsWalletInOrOutService walletInOrOutService;

    private static final String key = "cpsSettlement::";

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        log.info("用户结算收到消息：[{}]", new String(message.getBody()));
        List<WalletInOrOutRequest> list;
        try {
            list = JSONObject.parseArray(new String(message.getBody()), WalletInOrOutRequest.class);
        } catch (Exception e) {
            log.error("JSON解析消息出错 [{}]",e.getMessage());
            return Action.CommitMessage;
        }
        if(list.isEmpty()){
            return Action.CommitMessage;
        }
        String orderNo = list.get(0).getOrderNo();
        try {
            Boolean res = redisTemplate.opsForValue().setIfAbsent(key+orderNo,"用户结算",7, TimeUnit.DAYS);
            if(res!=null && !res){
                log.info("重复结算订单：[{}]", orderNo);
                return Action.CommitMessage;
            }
            walletInOrOutService.batchWalletIn(list);
            return Action.CommitMessage;
        } catch (Exception e) {
            redisTemplate.delete(key+orderNo);
            //消费失败，挂起当前队列
            log.error("用户结算出错 [{}]",e.getMessage());
            return Action.ReconsumeLater;
        }
    }
}
